// 下划线转换驼峰
function toHump(name) {
  return name.replace(/_(\w)/g, function(all, letter){
      return letter.toUpperCase();
  });
}
// 驼峰转换下划线
function toLine(name) {
  return name.replace(/([A-Z])/g,"_$1").toLowerCase();
}

function objKeyToHump(obj) {
  Object.keys(obj).forEach(key => {
    obj[toHump(key)] = obj[key];
  });
  return obj;
}

function getQueryObj() {
  let query = location.search.substring(1);
  let queryList = query.split('&');
  let obj = {};
  queryList.forEach(str => {
    let idx = str.indexOf('=');
    let key = decodeURIComponent(str.substring(0, idx));
    let value = decodeURIComponent(str.substring(idx + 1));
    obj[key] = value;
  });
  return obj;
}

// comporess img
const compressImg = (file) => new Promise((resolve) => {
  let canvas = document.createElement('canvas');
  let ctx = canvas.getContext('2d');

  let img = new Image();
  let url = URL.createObjectURL(file);

  img.onload = () => {
    URL.revokeObjectURL(url);

    let w, h;

    const ratio = img.height / img.width;
    w = Math.min(400, img.width);
    h = w * ratio;

    canvas.width = w;
    canvas.height = h;

    ctx.drawImage(img, 0, 0, w, h);
    canvas.toBlob(blob => {
      const f = new File([blob], file.name, {
        type: file.type,
        lastModified: file.lastModified
      });
      resolve(f);
    }, 'image/png');
  }
  
  img.src = url;
})

export default {
  toHump,
  toLine,
  objKeyToHump,
  getQueryObj,
  compressImg
}